home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 845 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  58 lines

  1. Path: maverick.tad.eds.com!news-admin@tad.eds.com
  2. From: fignet05.darrins@eds.com (Darrin Smith)
  3. Newsgroups: comp.lang.c
  4. Subject: To malloc (new) or not to malloc?  Clarification. Please ignore previous post.
  5. Date: 9 Jan 1996 17:55:09 GMT
  6. Organization: CUSD
  7. Message-ID: <4cua5t$dm@maverick.tad.eds.com>
  8. References: <4ctvk3$ort@maverick.tad.eds.com>
  9. NNTP-Posting-Host: 148.94.42.90
  10. Mime-Version: 1.0
  11. X-Newsreader: WinVN 0.93.11
  12.  
  13. A few of you sent me email stating that fread returns an integer.  You are of 
  14. course correct.  I didn't mean to say that fread returns a pointer, I was 
  15. just using shorthand to tell you that I was using fread to get the record to 
  16. store into the structure pointed to by sptr (that's why I wrote it as 
  17. sptr=fread(...).  Anyway, I should have been clearer.  Here it is again with 
  18. the shorthand taken out.
  19. _____________________________________________________________________________
  20.  
  21. I know that I should know the answer to this (I'm sure one of my past 
  22. instructors made it clear while I was sleep.... I mean sitting in class), 
  23. but I can't remember so...
  24.  
  25. Why is it that you can do something like the following:
  26.  
  27.         char *x;
  28.  
  29.         x="Some really long string with no particular meaning";
  30.  
  31. and have no problems, but can't (safely) do something like this:
  32.  
  33.         struct st1{char one[10];
  34.                    char two[20];
  35.                    char three[10];
  36.                   };
  37.  
  38.         st1 *sptr;      //or struct st1 *sptr in C instead of C++
  39.  
  40.     fread(sptr,sizeof(st1),1,infile);
  41.         
  42. This caused a program I was trying to debug to crash.  When I allocated 
  43. memory for sptr (I used sptr=new st1; but I suppose malloc would have done 
  44. just as well) it worked fine.                   
  45.  
  46.  
  47. What is going on here?  Why isn't memory set aside for st1 *sptr just as 
  48. it is for char *x?  Before I did the new (or malloc) it seemed as though 
  49. my program was getting written over!
  50.  
  51. Why?
  52.  
  53. Please respond here, or email me at: FIGNET05.darrins@eds.com
  54.  
  55. Thanks.
  56.  
  57.  
  58.